package com.epfresh.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.epfresh.adapter.GridBodyAdapter;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.*;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.utils.T;
import com.epfresh.bean.*;
import com.epfresh.global.BaseActivity;
import com.epfresh.global.BaseApplication;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.http.RequestManager;
import com.epfresh.api.ucrop.PhotoCore;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.universalimageloader.core.imageaware.ImageViewAware;
import com.epfresh.api.utils.FileUtil;
import com.epfresh.R;
import com.epfresh.location.PoiAddressActivity;
import com.google.gson.Gson;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by zhaozhenqiang on 2015/10/21.
 */
public class MyInfoActivity extends BaseActivity implements PhotoCore.PhotoResult {

    /*    @ViewInject(R.id.rl)
        private RelativeLayout rl;//二维码*/
    private LinearLayout code_plate;//二维码
    private ImageView imageview;//二维码的功能还是比较麻烦的，暂时保留
    private ImageView headImage;
    private LinearLayout my_code;
    private TextView nicknameTV;
    private TextView tv_body_class;
//    String accountId = "";
//    String token = "";
//    String nickname;

    private PhotoCore photoCore;
    private String filePath = FileUtil.getImgCacheDir() + "/" + "avatar";

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        filePath = filePath + "_" + getUser().getAccountId();
        initView();
        ivBack.setVisibility(View.VISIBLE);

        photoCore = new PhotoCore(this, this);
        photoCore.setResultHeight(200);
        photoCore.setResultWidth(200);
        updateAvatar(getUser().getAvatar());
/*
        updateUserProfile();
*/

        tv_1 = (TextView) findViewById(R.id.tv_1);
        tv_2 = (TextView) findViewById(R.id.tv_2);
        tv_1Background = (GradientDrawable)tv_1.getBackground();
        tv_2Background = (GradientDrawable)tv_2.getBackground();

        tv_1.setOnClickListener(this);
        tv_2.setOnClickListener(this);
/*        adapter = new GridBodyAdapter(this,10);
        GridView gridView = (GridView) findViewById(R.id.gv_body);
        gridView.setAdapter(adapter);
        adapter.setOnItemClickListener(this);*/

        updateUserProfile();

    }
    TextView tv_1,tv_2;
    GradientDrawable tv_1Background,tv_2Background;
    int preferenceFlag = 3;//0，全部；1，清真；


    @Override
    protected void onResume() {
        nicknameTV.setText(getUser().getNickname());
        super.onResume();
    }

    public void initView() {
        setContentView(R.layout.activity_myinfo);
        headImage = (ImageView)findViewById(R.id.image_head);
        nicknameTV = (TextView)findViewById(R.id.nickname);
        tv_body_class = (TextView)findViewById(R.id.tv_body_class);
        View rl = findViewById(R.id.rl);
        rl.setOnClickListener(this);
        headImage.setOnClickListener(this);
        LinearLayout edit = (LinearLayout)findViewById(R.id.edit_nickname);
        edit.setOnClickListener(this);
        toolbarTitle.setText("账户管理");
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK )
        {
            if(userBody!=null&&userBody.getPreference() != preferenceFlag) {
                Intent intent = new Intent(this, HomeActivity.class);
/*                intent.putExtra("preference_flag", 1);
                intent.putExtra("home_tab_index", 3);*/
                com.epfresh.api.entity.City city = ApplicationHelper.getInstance().getCity();
                intent.putExtra("cityId", city.getCityId());
                intent.putExtra("cityName", city.getCityName());
                startActivity(intent);
            }
            finish();
        }
        return false;
    }
    public void onClick(View view) {
/*

        if(view.getTag(R.id.item_key_status) instanceof Integer){
            if((int)view.getTag(R.id.item_key_status) != adapter.flagPosition)
                toast("如需修改，请联系客服400-0588-198");
            return;
        }
*/

        super.onClick(view);
        switch (view.getId()) {
            case R.id.baseback:
                // 返回上一页
                if(userBody!=null&&userBody.getPreference() != preferenceFlag) {
                    Intent intent = new Intent(this, HomeActivity.class);
                    com.epfresh.api.entity.City city = ApplicationHelper.getInstance().getCity();
                    intent.putExtra("cityId", city.getCityId());
                    intent.putExtra("cityName", city.getCityName());
                    startActivity(intent);
                }

                finish();
                break;
            case R.id.image_head:
            case R.id.rl:
                photoCore.showPhotoDialog(Uri.fromFile(new File(filePath)),filePath, false);
                break;
            case R.id.tv_1:
                initPreference(1);
                mHttpUp();
                break;
            case R.id.tv_2:
                initPreference(0);
                mHttpUp();
                break;
/*            case R.id.my_code:
                    *//*显示二维码，最显示的边距做了调整，有必要进一步优化显示效果,,,,该功能短期内暂停，方法实现在最下面*//*
                code_plate.setVisibility(View.VISIBLE);
                createImage();
                break;*/
            case R.id.edit_nickname:
                toast("如需修改，请联系客服400-0588-198");
                /*Intent edit = new Intent(this, EditNicknameActivity.class);

                startActivity(edit);*/
                break;
            case R.id.rl_address:
                Intent intent = new Intent(this, ReceiverAddressActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        // 用户没有进行有效的设置操作，返回
        if (resultCode == RESULT_CANCELED) {
            Toast.makeText(getApplication(), "取消", Toast.LENGTH_LONG).show();
            return;
        }

        photoCore.onResult(requestCode, resultCode, intent);
        super.onActivityResult(requestCode, resultCode, intent);
    }

    private void mPicUp(String id) {
        RequestEntityPurchase<Map<String, String>> data = new RequestEntityPurchase<>();
        data.setCmd(AppPurchaseRouterConstant.cmd_account_acc_updateAvatar);
        //data.setToken(getUser().getToken());
        Map<String, String> map = new HashMap<>();
        map.put("id", getUser().getAccountId());
        map.put("avatarImgId", id);
        data.setParameters(map);
        request(data, AppPurchaseRouterConstant.cmd_account_acc_updateAvatar, onRequestListenerUp);
    }

    OnRequestListener<StatusEntity> onRequestListenerUp = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }
        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
            StatusEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                getUser().delDeliveryAddressCount();
                toast(BaseApplication.getDoc().getBeenSubmitted());
            }
            updateUserProfile();
        }
    };
    UserBody userBody;
    OnRequestListener<UserBody> onRequestListener = new OnRequestListener<UserBody>() {
        @Override
        public UserBody jsonToObj(String responseStr) {


            return new Gson().fromJson(responseStr, UserBody.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<UserBody> response, Object tag) {
            userBody = response.getResponseElement();
            User user = new User();
            user.setAccess_token(getUser().getAccess_token());
            user.setAccountId(getUser().getAccountId());
            user.setPassword(getUser().getPassword());
            user.setTag(UUID.randomUUID().toString());

            user.setPhone(userBody.getPhone());
            user.setNickname(userBody.getNickname());
            user.setHasDeliveryAddress(userBody.isHasDeliveryAddress());
            user.setHasCert(userBody.isHasCert());
            user.setCertStatus(userBody.getCertStatus());
            user.setDeliveryAddressCount(userBody.getDeliveryAddressCount());
            user.setAvatar(userBody.getAvatar());
            tv_body_class.setText(userBody.getSubjectName());
/*
            adapter.flagPosition = userBody.getSubjectType();
            adapter.notifyDataSetChanged();*/
            initPreference(userBody.getPreference());

            updateUser(user);

            nicknameTV.setText(user.getNickname());
            updateAvatar(user.getAvatar());
        }
    };
    void initPreference(int i){
        preferenceFlag = i;
        int colorGrey = Color.parseColor("#999999");
        int colorGreen = Color.parseColor("#3eb049");
        tv_1.setTextColor(colorGrey);
        tv_1Background.setStroke(1,colorGrey);
        tv_2.setTextColor(colorGrey);
        tv_2Background.setStroke(1,colorGrey);
        if(i==0){
            tv_2.setTextColor(colorGreen);
            tv_2Background.setStroke(1,colorGreen);
        }else {
            tv_1.setTextColor(colorGreen);
            tv_1Background.setStroke(1,colorGreen);
        }
    }

    public void updateUserProfile() {

        String token = getUser().getAccess_token();
        if (token == null || "".equals(token)) {
            Intent intent = new Intent(mContext, LoginActivity.class);
            intent.putExtra("flag", "main");
            startActivity(intent);

        } else {
            RequestEntityPurchase<Map<String, String>> data = new RequestEntityPurchase<>();
            data.setCmd(AppPurchaseRouterConstant.cmd_account_acc_profile);
            //data.setToken(getUser().getToken());

            Map<String, String> map = new HashMap<>();
            map.put("accountId", getUser().getAccountId());

            data.setParameters(map);
            request(data, AppPurchaseRouterConstant.cmd_account_acc_profile, onRequestListener);
        }
    }


    RequestTag tag = new RequestTag();

    OnRequestListener<FileUploadResponse> uploadListener = new OnRequestListener<FileUploadResponse>() {
        @Override
        public FileUploadResponse jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, FileUploadResponse.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<FileUploadResponse> response, Object tag) {
            RequestTag requestTag = (RequestTag) tag;

            FileUploadResponse responseElement = response.getResponseElement();
            int id = responseElement.getId();
            if (id == Integer.MIN_VALUE) {
                toast("图片上传失败");
                return;
            }

            mPicUp(id + "");

        }
    };

    public void uploadImage(String filePath, int id) {

        try {
            String file = FileUtil.encodeBase64File(filePath);
            RequestEntityPurchase<Map<String, String>> data = new RequestEntityPurchase<>();
            data.setCmd(AppPurchaseRouterConstant.cmd_account_file_upload);
            //data.setToken(getUser().getToken());

            Map<String, String> map = new HashMap<>();
            map.put("ext", "jpg");
            map.put("file", file);

            data.setParameters(map);


            tag.tag = AppPurchaseRouterConstant.cmd_account_file_upload;
            tag.action = id;
            request(data, tag, uploadListener);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updateAvatar(String url) {
        String urlHead = null;
        if (url != null) {
            String[] split = url.split("-AVATAR?");
            if (split.length > 1) {
                urlHead = split[0];
            }
        }
        if (urlHead == null) {
            urlHead = url;
        }
        ImageLoader.getInstance().displayImage(urlHead, new ImageViewAware(headImage), BaseApplication.getAvatarOptions(url), null, null, null);
    }

    @Override
    public void onSuccess(String path) {
//        updateAvatar(path);
        uploadImage(filePath, 0);
    }

    @Override
    public void onFail(String msg) {

    }

    @Override
    public void onReupload() {

    }

    @Override
    protected void onDestroy() {
        RequestManager.getInstance().cancel(tag);
        super.onDestroy();
    }


    /**
     * 提交修改
     */
    private void mHttpUp() {

        RequestEntityPurchase<Map<String, String>> data = new RequestEntityPurchase<>();

        data.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_account_acc_editPreference);
        Map<String, String> map = new HashMap<>();
        //data.setToken(getUser().getToken());
        map.put("id", getUser().getAccountId());
        map.put("preference", ""+preferenceFlag);//偏好设置（0：查看全部商品 1：只查看清真商品）
        data.setParameters(map);
        request(data, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_account_acc_editPreference, onUpPreferenceRequestListener);
    }

    OnRequestListener<StatusEntity> onUpPreferenceRequestListener = new OnRequestListener<StatusEntity>() {
        @Override
        public StatusEntity jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, StatusEntity.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            T.toast("修改出现异常，请稍后再试");
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            T.toast("修改出现异常，请稍后再试");
        }

        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<StatusEntity> response, Object tag) {
            hideProgressDialog();
            StatusEntity responseElement = response.getResponseElement();
            if (responseElement.isSuccess()) {
                T.toast("修改成功");
                return;
            }
            T.toast("修改出现异常，请稍后再试");
        }
    };


}
